﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace EstateMan.DataAccess.Repository.Implementaion
{
    public class Repository<T> : IRepository<T> where T : class
    {
        private readonly IDbContext _context;
        private readonly IDbSet<T> _dbSet;

        public Repository(IDbContext ctx)
        {
            _context = ctx;
            _dbSet = _context.Set<T>();
        }

        public T Add(T entity)
        {
            return _dbSet.Add(entity);
        }

        public void Delete(T entity)
        {
            _dbSet.Remove(entity);
        }

        public T Find(Expression<Func<T, bool>> predicate)
        {
            return _dbSet.FirstOrDefault(predicate);
        }

        public T Find(params object[] keys)
        {
            return _dbSet.Find(keys);
        }


        public void Update(T entity)
        {
            var entry = _context.Entry(entity);
            _dbSet.Attach(entity);
            entry.State = EntityState.Modified;
        }


        public IQueryable<T> Filter(Expression<Func<T, bool>> filter, out int total, int index = 0, int size = 10)
        {
            int skip = index * size;
            var resultSet = (filter == null)
                                ? _dbSet.AsQueryable()
                                : _dbSet.Where(filter).AsQueryable();
            resultSet = (skip > 0) ? resultSet.Take(size) : resultSet.Skip(index).Take(size);

            total = resultSet.Count();
            return resultSet;
        }
    }
}

